package com.jy.project.service.imp.abstr;

import com.jy.project.domain.Apply;
import com.jy.project.domain.User;
import com.jy.project.dto.ApplyDTO;
import com.jy.project.ex.BizException;
import com.jy.project.mapper.ApplyMapper;
import com.jy.project.mapper.UserMapper;
import com.jy.project.util.CodeUtils;
import com.jy.project.util.JwtUtils;
import com.jy.project.vo.MaterialVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("abstractApplyBusiness")
public abstract class AbstractApplyBusiness {

    @Autowired
    private ApplyMapper applyMapper;


    @Autowired
    private UserMapper userMapper;


    public abstract void checkApplyNo(String applyNo);


    public abstract MaterialVO checkMaterialNo(String materialNo);

    public Apply create(){
        Apply apply = new Apply();
        Date date = new Date();
        apply.setCreateAt(date);
        apply.setUpdateAt(date);
        apply.setUpdateDay(date);
        apply.setIsDelete(0);
        return  apply;
    }

    public boolean insertApplyBusiness(ApplyDTO dto){
        if (dto==null){
            throw new BizException("Apply对象为空");
        }
        checkApplyNo(dto.getApplyNo());
        MaterialVO materialVO = checkMaterialNo(dto.getMaterialNo());
        Apply ay = this.create();
        ay.setName(dto.getName());
        ay.setApplyType(dto.getApplyType());
        ay.setMaterialNo(dto.getMaterialNo());
        ay.setMaterialName(materialVO.getName());
        //制单人
        String token = dto.getToken();
        User u = JwtUtils.verifyToken(token);
        Long id = u.getId();
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null){
            throw  new BizException("用户信息找不到或已被删除");
        }
        ay.setApplicantCompanyNo(user.getCompanyNo());
        ay.setApplicantCompanyName(user.getCompanyName());
        ay.setApplicantDeptNo(user.getDeptNo());
        ay.setApplicantDeptName(user.getDeptName());
        ay.setApplicantUserId(user.getId());
        ay.setApplicantUserNickName(user.getNickName());
        //使用人
        if (dto.getUseUserId()!=null&&dto.getUseUserId()!=0){
            User useUser = userMapper.selectByPrimaryKey(dto.getUseUserId());
            if (useUser==null){
                throw  new BizException("使用者用户信息找不到");
            }
            ay.setUseCompanyNo(useUser.getCompanyNo());
            ay.setUseCompanyName(useUser.getCompanyName());
            ay.setUseDeptNo(useUser.getDeptNo());
            ay.setUseDeptName(useUser.getDeptName());
            ay.setUseUserId(useUser.getId());
            ay.setUseNickName(useUser.getNickName());
        }
        ay.setExt(dto.getExt());
        ay.setRemarks(dto.getRemarks());
        return  applyMapper.insertSelective(ay)>0;
    }
}
